﻿/// <reference path="../Framework/linq-vsdoc.js" />

namespace("Sieena.Home");

(function ($, undefined) {

//Sieena.Home.Index
Sieena.Home.Index = (function () {

    //Internal variables
    var
    _people, 
    _peopleData, 
    _peopleContainers, 
    _currentPeople, 
    _notices, 
    _noticeContainer,
    _twitterPosts,
    _peopleFirstLoad = true,
    _noticeFirstLoad = true,
    _twitterFirstLoad = true;

    //Private Methods
    function load()
    {
        loadPeople();
        loadNotices();
        loadEvents();
        loadTwitter();
        loadDate();
        loadTime()
        loadWeather();
        
        Sieena.Objects.Clock().Init();
        $(document).everyTime(Sieena.Configuration.ReloadTimes.Date, function(){ loadDate(); });
        $(document).everyTime(Sieena.Configuration.ReloadTimes.Time, function(){ loadTime(); });
        $(document).everyTime(Sieena.Configuration.ReloadTimes.Weather, function(){ loadWeather(); });
        $(document).everyTime(Sieena.Configuration.ReloadTimes.EventData, function(){ loadEvents(); });
    }

    function loadDate()
    {
        var currentDate = new Date();

        $(".title .day").html(Sieena.Common.GetMonthName(currentDate.getMonth() + 1));
        $(".title .num-day").html(Sieena.Common.GetDayText(currentDate.getDate()));
        $(".title .year").html(currentDate.getFullYear());
    }

    function loadTime()
    {
        var currentDate = new Date();   

        var hours = currentDate.getHours().toString().lpad("0", 2).toString();
        var minutes = currentDate.getMinutes().toString().lpad("0", 2).toString();

        $(".title-left .hour span:first").html(hours);
        $(".title-left .hour .minutes").html(minutes);
        $(".title-left .today").html(currentDate.getDayName());
    }

    function loadEvents()
    {
        $.ajax({
            url: "/Home/Events",
            type: 'GET',
            success: function (html) {
                $('.my-events').empty();
                $('.my-events').html(html);
                $('.my-events').cycle({ 
                    fx:      Sieena.Configuration.EventFx, 
                    timeout: Sieena.Configuration.ReloadTimes.EventTimeout, 
                    delay:   Sieena.Configuration.ReloadTimes.EventDelay
                });

                Sieena.Common.DisplayNotification('success', 'Message', "Success trying to acquire events data"); 
            }
        });        

    }

    function loadWeather()
    {
        $("#item13").empty();
        $("#item13").weatherfeed([Sieena.Configuration.LocalCityCode]);
        Sieena.Common.DisplayNotification('success', 'Message', "Success trying to acquire weather data"); 
    }

    function loadTwitter()
    {
        _twitterPosts = [];

        $.getJSON("http://search.twitter.com/search.json?rpp=5&callback=?", { q: Sieena.Configuration.TwitterHashtag },
            function(data) {
            _twitterPosts = data.results;

            if(_twitterFirstLoad)
            {
                setRandomTwitterPost();    
                $(document).everyTime(Sieena.Configuration.ReloadTimes.TwitterPost, function(){ setRandomTwitterPost(); });
                $(document).everyTime(Sieena.Configuration.ReloadTimes.TwitterData, function(){ loadTwitter(); });
                _twitterFirstLoad = false;
            }

            Sieena.Common.DisplayNotification('success', 'Message', "Success trying to acquire twitter data");    
        });
    }

    function getRandomTwitterPost(current)
    {
        var index = $.randomBetween(0, _twitterPosts.length - 1);
        var post = _twitterPosts[index];

        if(post != undefined && post != null && post.id_str == current) return getRandomTwitterPost(current);
        return post;
    }

    function setRandomTwitterPost()
    {
        var personAccount = $(".twitter .tweeters");
        var tweet = $(".twitter .tweet");
        var id = $(".twitter .tweetId");

        var current = $(".twitter .tweetId").html();
        var post = getRandomTwitterPost(current);

        if(post != undefined && post != null){
            
            $(personAccount).fadeOut('slow', function() {
                $(this).html("@{0}".format(post.from_user));
            }).fadeIn('slow');

            $(tweet).fadeOut('slow', function() {
                $(this).html(post.text);
            }).show('slow');

            $(id).html(post.id_str);
        }
    }

    function getRandomNotice(current)
    {
        var index = $.randomBetween(0, _notices.length - 1);
        notice = _notices[index];

        var used = notice.Title == current;

        if(used) return getRandomNotice(current);
        return notice;
    }

    function setNoticeData(container, notice)
    {
        var objContainer = $(".ad");

        if(notice == null || notice == undefined)
        {
            var current = objContainer.find("h1:first").html();
            notice = getRandomNotice(current);
        }

        if(notice != null && notice != undefined)
        {
            var title = objContainer.find("h1:first");
            var summary = objContainer.find(".ad-text");
            var date = objContainer.find("span:first");
            var dateValueObj = notice.Date.dateFromJson();

            var dateValue = "{0} {1}, {2}".format(
                dateValueObj.getMonthName(), 
                dateValueObj.getDate(), 
                dateValueObj.getFullYear()
            );

            $(objContainer).hide('slide',{ direction: "left" }, 'slow', function() 
            {
                $(title).html(notice.Title);
                $(date).html(dateValue);
                $(summary).html(notice.Summary);
            }).show('slide',{ direction: "right" }, 'slow');
        }

    }

    function loadNotices()
    {
       _noticeContainer = "ad";

        $.ajax({
            url: "Home/LoadNotices",
            type: "GET",
            dataType: "json",
            success: function(data){ 
                _notices = data;
                /* INITIAL SET  */       
                var notice = Enumerable.From(_notices)
                        .Where(function(n) { return (n.StartDate.dateFromJson() >= new Date()) && (n.EndDate.dateFromJson() <= new Date()); })
                        .FirstOrDefault();

                if(_noticeFirstLoad)
                {
                    setNoticeData(_noticeContainer, notice);
                    $(document).everyTime(Sieena.Configuration.ReloadTimes.NoticePost, function(){ setNoticeData(_noticeContainer) });
                    $(document).everyTime(Sieena.Configuration.ReloadTimes.NoticeData, function(){ loadNotices() });
                    _noticeFirstLoad = false;
                }
                
                /* ************ */
                Sieena.Common.DisplayNotification('success', 'Message', "Success trying to acquire notices data");    
            },
            error: function(){ 
                
            }
        });
    }

    function getRandomPerson(currentName)
    {
        var index = $.randomBetween(0, _peopleData.length - 1);
        var person = _peopleData[index];

        var current = person.FullName == currentName;
        var used = Enumerable.From(_currentPeople).Any(function(p) { return p.FullName == person.FullName });

        if(used || current) return getRandomPerson(currentName);
        return person;
    }

    function setPeopleData(container, person)
    {
        /* CONTAINER SET */

        if(container == null)
            container = _peopleContainers[$.randomBetween(0, _peopleContainers.length - 1)];

        var objContainer = $("#{0}".format(container));
        var icon = objContainer.find("div:first");
        var img = objContainer.find("img:first");
        var day = objContainer.find(".day-number");
        var name = objContainer.find("span[name='personName']");
        var fullName = objContainer.find("span[name='fullpersonname']");

        /* PERSON SET */

        if(_currentPeople.length > 1)
        {
            var current = Enumerable.From(_currentPeople);
            var currentName = $(fullName).html();

            var currentPerson = current
                .Where(function(p) { return p.FullName == currentName })
                .SingleOrDefault();

            if(currentPerson != null)
            {
                var currentIndex = current.IndexOf(currentPerson);
                _currentPeople.splice(currentIndex, 1);
            }
        }

        if(person == null) person = getRandomPerson(currentName);
        _currentPeople.push(person);

        /* HTML SET */
        
        $(icon).removeClass("birthday-icon");
        $(icon).removeClass("award-icon");
        $(icon).removeClass("bookmark-icon");
        $(icon).removeClass("ic-birthday");
        $(icon).removeClass("ic-award");
        $(icon).removeClass("ic-bookmark");

        if(container=="item11")
        {
            switch(person.ItemType)
            {
                case Sieena.Configuration.PersonItemType.Birthday: 
                    $(icon).addClass("birthday-icon");
                    break;
                case Sieena.Configuration.PersonItemType.Birthday: 
                    $(icon).addClass("award-icon");
                    break;
                case Sieena.Configuration.PersonItemType.Birthday: 
                    $(icon).addClass("bookmark-icon");
                    break;
            }
        }
        else
        {
            switch(person.ItemType)
            {
                case Sieena.Configuration.PersonItemType.Birthday: 
                    $(icon).addClass("ic-birthday");
                    break;
                case Sieena.Configuration.PersonItemType.Birthday: 
                    $(icon).addClass("ic-award");
                    break;
                case Sieena.Configuration.PersonItemType.Birthday: 
                    $(icon).addClass("ic-bookmark");
                    break;
            }
        }

        $(objContainer).fadeOut('slow', function() 
        {
            $(img).attr("src", person.PhotoURL);
            $(day).html(person.Date.getDate());
            $(name).html(person.FirstName);
            $(fullName).html(person.FullName);            

        }).fadeIn('slow');

    }

    function loadPeopleData()
    {
        var currentDate = new Date();
        var currentDayOfYear = currentDate.getDayOfYear();

        var maxBirthdayDate = new Date().addDays(Sieena.Configuration.DateRanges.MaxBirthday);
        var maxBirthdayDayOfYear = maxBirthdayDate.getDayOfYear();

        var minWelcomeDate = new Date().addDays(Sieena.Configuration.DateRanges.MinWelcome);
        var maxWelcomeDate = new Date().addDays(Sieena.Configuration.DateRanges.MaxWelcome);

        var minAnniversary = new Date().addDays(Sieena.Configuration.DateRanges.MinAnniversary);
        var minAnniversaryDayOfYear = minAnniversary.getDayOfYear();

        var birthdays = Enumerable.From(_people)
            .Where(function(p) { return (p.Birthday.dateFromJson().getDayOfYear() >= currentDayOfYear) && (p.Birthday.dateFromJson().getDayOfYear() <= maxBirthdayDayOfYear); })
            .Select(function(p) {
                return {
                    FirstName: p.FirstName,
                    FullName: p.FullName,
                    Date: p.Birthday.dateFromJson(),
                    ItemType: Sieena.Configuration.PersonItemType.Birthday,
                    PhotoURL: p.PhotoURL
                };
            });

        var admissions = Enumerable.From(_people)
            .Where(function(p) { return (p.Admission.dateFromJson() >= minWelcomeDate) && (p.Admission.dateFromJson() <= maxWelcomeDate); })
            .Select(function(p) {
                return {
                    FirstName: p.FirstName,
                    FullName: p.FullName,
                    Date: p.Admission.dateFromJson(),
                    ItemType: Sieena.Configuration.PersonItemType.Welcome,
                    PhotoURL: p.PhotoURL
                };
            });

        var anniversaries = Enumerable.From(_people)
            .Where(function(p) { return (p.Admission.dateFromJson().getDayOfYear() >= minAnniversaryDayOfYear) && (p.Admission.dateFromJson().getDayOfYear() <= currentDayOfYear); })
            .Select(function(p) {
                return {
                    FirstName: p.FirstName,
                    FullName: p.FullName,
                    Date: p.Admission.dateFromJson(),
                    ItemType: Sieena.Configuration.PersonItemType.Anniversary,
                    PhotoURL: p.PhotoURL
                };
            });             


        _peopleData = birthdays.Union(admissions).Union(anniversaries).ToArray();
    }

    function loadPeople()
    {
        _peopleContainers = [ "item11", "item33", "item44", "item45", "item46"];
        _currentPeople = [];

        var personIndex = 0;

        $.ajax({
            url: "Home/LoadPeople",
            type: "GET",
            dataType: "json",
            success: function(data){ 

                _people = data;
                loadPeopleData();
                /* INITIAL SET  */
                if(_peopleFirstLoad)
                {
                    Enumerable.From(_peopleContainers).ForEach(function(container){
                        var currentPerson = Enumerable.From(_peopleData)
                                .Skip(personIndex)
                                .FirstOrDefault();

                        setPeopleData(container, currentPerson);
                        personIndex++;
                    });

                     $(document).everyTime(Sieena.Configuration.ReloadTimes.PersonPost, function(){ setPeopleData(); });
                     $(document).everyTime(Sieena.Configuration.ReloadTimes.PersonData, function(){ loadPeople(); });
                     _peopleFirstLoad = false;
                }
                /* ************ */
                Sieena.Common.DisplayNotification('success', 'Message', "Success trying to acquire personnel data");    
            },
            error: function(){ 
                Sieena.Common.DisplayNotification('error', 'Message', "Ooops, something went wrong");    
            }
        });
    }

    //Expose Public Methods
    return {
        Load : load
    };

});


})(jQuery);